// 引入数据库模块
const db = require('../mysql/index')
const { getNowTime,getDate } = require('../common/common')
const checkParam = require('../utils/checkParam')
const mysql2 = require('../mysql/mysqlTools')
const log4js = require('../utils/log4')
const prisma = require('../utils/prisma')
const logger = log4js.getLogger(`server/router_handler/admin.js`)
const convertToChinaTime = require('../utils/convertToChinaTime')
const { QueryDb,savePhotoFile } = require('../utils/index')

// 获取用户信息
exports.getUserInfo = async (req, res) => {
  const sql = `
  SELECT
  	admin.id,
    admin.nickname,
    admin.username,
  	admin.mobile,
    admin.user_pic,
    admin_roles.role_id,
    roles.name AS role_name,
    permissions.name AS permission_name,
    permissions.type AS permission_type
  FROM
    admin
  LEFT JOIN
    admin_roles ON admin.id = admin_roles.admin_id
  LEFT JOIN
    roles ON admin_roles.role_id = roles.id
  LEFT JOIN
    role_permissions ON roles.id = role_permissions.role_id
  LEFT JOIN
    permissions ON role_permissions.permission_id = permissions.id
  WHERE
    admin.id = ${req.user.id}  
  `
  try {
    const data = await mysql2.reader(sql)
    const userInfo = {
      id: data[0].id,
      nickname: data[0].nickname,
      username: data[0].username,
      mobile: data[0].mobile,
      user_pic: data[0].user_pic,
      roleId: data[0].role_id,
      name: data[0].role_name
    }
    const menus = []
    const points = []
    data.forEach(i => {
      if (i.permission_type && i.permission_type === 'route') {
        menus.push(i.permission_name)
      }
      if (i.permission_type && i.permission_type === 'button') {
        points.push(i.permission_name)
      }
    })
    const roles = { menus, points }
    userInfo['roles'] = roles
    return res.send({
      status: 1,
      message: '获取资料成功',
      data: userInfo
    })
  } catch (error) {
    return res.cc(error)
  }
}

// 管理员列表
exports.adminList = async (req, res) => {
  let { pageNumber, pageSize, nickname } = req.body
  pageNumber = pageNumber ? Number(pageNumber) : 1
  pageSize = pageSize ? Number(pageSize) : 10
  const total = await prisma.admin.count({
    where: {
      is_del: 0,
      // is_able: 1
    }
  })
  let getUser = await prisma.admin.findMany({
    skip: (pageNumber - 1) * pageSize,
    take: pageSize,
    where: {
      is_del: 0,
      // is_able: 1
    }, select: {
      id: true,
      is_able: true,
      nickname: true,
      username: true,
      user_pic: true,
      mobile: true,
      create_time: true,
      remarks:true
    }
  })
  // console.log(getUser)
  for (let index = 0; index < getUser.length; index++) {
    getUser[index].is_able = getUser[index].is_able == 1 ? true : false
    getUser[index].create_time = getDate(getUser[index].create_time)
    // console.log(getUser[index].create_time) 
    const roleId = await prisma.admin_roles.findMany({
      where: {
        admin_id: getUser[index].id
      }, select: {
        role_id: true,
      }
    })
    getUser[index].roleId = roleId[0].role_id
    const username = await prisma.roles.findMany({
      where: {
        id: getUser[index].roleId
      }, select: {
        name: true,
      }
    })
    getUser[index].name = username[0].name
    const role_permission = await prisma.role_permissions.findMany({
      where: {
        role_id: getUser[index].roleId
      }, select: {
        permission_id: true,
      }
    })
    getUser[index].permission_id = []
    role_permission.map((item, t) => {
      getUser[index].permission_id.push(item.permission_id)
    })
    let permission
    // console.log(role_permission)
    getUser[index].permission_name = []
    getUser[index].desc = []
    for (let j = 0; j < role_permission.length; j++) {
      // console.log(role_permission[j].permission_id)
      permission = await prisma.permissions.findMany({
        where: {
          id: role_permission[j].permission_id
        }, select: {
          desc: true,
          name: true
        }
      })
      getUser[index].permission_name.push(permission[0].name)
      getUser[index].desc.push(permission[0].desc)
    }
  }
  // console.log(total)
  return res.send({
    status: 1,
    message: '获取用户列表成功',
    data: getUser,
    total: total
  })
}

// 角色列表选项option
exports.roleListOption = (req, res) => {
  const sql = `SELECT id AS value, name AS label FROM roles`
  db.query(sql, (err, data) => {
    if (err) return res.cc(err)
    return res.send({
      status: 1,
      message: '获取角色列表成功',
      data: data
    })
  })
}

// 更新管理员信息
exports.updateAdmin = async(req, res) => {
  const checks = checkParam(req.body, ['id', 'nickname', 'username', 'name', 'is_able', 'mobile'])
  if (checks) {
    return res.send({
      status: 0,
      message: `缺少参数: ${checks}`
    })
  }
  let { id, nickname, username, name, user_pic, is_able, mobile } = req.body
  console.log(id, nickname, username, name, user_pic, is_able, mobile)
  const GetUserPic = await QueryDb(`select user_pic from admin where id = ${id}`)
  user_pic = GetUserPic[0].user_pic
  if(req.files){
    const imgName = await savePhotoFile(req.files.file)
    user_pic =  imgName
  }
  const regex = /^[1-9]\d{10}$/
  if (!regex.test(mobile)) return res.cc('手机号格式不正确')

  const sql = `UPDATE admin SET nickname = ?, username = ?, user_pic = ? ,is_able = ?, mobile = ? WHERE id = ?`
  db.query(sql, [nickname, username, user_pic, is_able, mobile, id], (err, data) => {
    if (err) return res.cc(err)
    const sql = `UPDATE admin_roles SET role_id = ? WHERE admin_id = ?`
    db.query(sql, [name, id], (err, data) => {
      if (err) return res.cc(err)
      logger.debug('data2', data)
      return res.send({
        status: 1,
        message: '更新管理员信息成功'
      })
    })
  })
}

// 删除管理员
exports.deleteAdmin = (req, res) => {
  const id = req.params.id
  if (!id) return res.cc('缺少id参数')
  const sql = `UPDATE admin SET is_del = 1 WHERE id = ?`
  db.query(sql, [id], (err, data) => {
    if (err) return res.cc(err)
    return res.send({
      status: 1,
      message: '删除管理员成功'
    })
  })
}

// 角色列表展示
exports.roleList = (req, res) => {
  let { pageNumber, pageSize } = req.query
  pageNumber = pageNumber ? Number(pageNumber) : 1
  pageSize = pageSize ? Number(pageSize) : 10
  const sql = `SELECT roles.id, roles.name, roles.desc FROM roles  LIMIT ${(pageNumber - 1) * pageSize}, ${pageSize}`
  db.query(sql, (err, data) => {
    if (err) return res.cc(err)
    // 计算总条数
    const sql = `SELECT COUNT(*) AS count FROM roles`
    db.query(sql, (err, count) => {
      if (err) return res.cc(err)
      return res.send({
        status: 1,
        message: '获取角色列表成功',
        data: data,
        total: count[0].count
      })
    })
  })
}

// 获取权限列表
exports.permissionList = (req, res) => {
  const sql = `SELECT * FROM permissions`
  db.query(sql, (err, data) => {
    if (err) return res.cc(err)
    return res.send({
      status: 1,
      message: '获取权限列表成功',
      data: data
    })
  })
}

// 获取角色的权限点
exports.getRolePermissions = (req, res) => {
  if (!req.query.id || isNaN(req.query.id) || req.query.id == undefined) return res.cc('id参数有误')
  const id = req.query.id
  const sql = `
    SELECT permissions.id, permissions.name, permissions.desc
    FROM roles
    LEFT JOIN role_permissions ON roles.id = role_permissions.role_id
    LEFT JOIN permissions ON role_permissions.permission_id = permissions.id
    WHERE roles.id = ${id}
  `
  db.query(sql, (err, data) => {
    if (err) return res.cc(err)
    let result = null
    if ((data.length === 1 && data[0].desc === null) || data.length === 0) {
      result = []
    } else {
      result = data
    }
    return res.send({
      status: 1,
      message: '获取角色权限点成功',
      data: result
    })
  })
}

// 更新角色的权限点
exports.updateRolePermissions = async (req, res) => {
  const checks = checkParam(req.body, ['id', 'permissionIds'])
  if (checks) {
    return res.send({
      status: 0,
      message: `缺少参数: ${checks}`
    })
  }
  const { id, permissionIds } = req.body
  if (!Array.isArray(permissionIds)) res.cc('permissionIds参数类型有误')

  try {
    // 先获取该角色原有的权限点，避免删除后恢复
    const t = await mysql2.reader(`SELECT permission_id FROM role_permissions WHERE role_id = ${id}`)
    const olePermission = t.map(item => item.permission_id)

    try {
      // 删除原有的权限点
      await mysql2.writer(`DELETE FROM role_permissions WHERE role_id = ?`, [id])
      for (let permissionId of permissionIds) {
        await mysql2.writer(`INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)`, [id, permissionId])
      }
      return res.send({ status: 1, message: '更新权限点成功' })
    } catch (error) {
      logger.error(error)
      for (let olePermissionId of olePermission) {
        await mysql2.writer(`INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)`, [id, olePermissionId])
      }
    }
  } catch (error) {
    return res.cc(error)
  }
}

// 更新角色信息
exports.updateRole = async (req, res) => {
  const checks = checkParam(req.body, ['id', 'name', 'desc'])
  if (checks) {
    return res.send({
      status: 0,
      message: `缺少参数: ${checks}`
    })
  }
  const { id, name, desc } = req.body
  if (isNaN(id)) return res.cc('id参数有误')
  if (id === 1) return res.cc('超级管理员不能修改')
  try {
    await mysql2.writer(`UPDATE roles SET roles.name = ?, roles.desc = ? WHERE id = ?`, [name, desc, id])
    return res.send({ status: 1, message: '更新角色信息成功' })
  } catch (error) {
    return res.cc(error)
  }
}

// 添加角色
exports.addRole = async (req, res) => {
  const checks = checkParam(req.body, ['name', 'desc'])
  if (checks) {
    return res.send({
      status: 0,
      message: `缺少参数: ${checks}`
    })
  }
  try {
    await mysql2.writer(`INSERT INTO roles (roles.name, roles.desc) VALUES (?, ?)`, [req.body.name, req.body.desc])
    res.send({ status: 1, message: '添加角色成功' })
  } catch (error) {
    res.cc(error)
  }
}

// 更新cms导航栏用户信息
exports.updateCmsNav = async (req, res) => {
  const checks = checkParam(req.body, ['nickname', 'mobile', 'id'])
  if (checks) {
    return res.send({
      status: 0,
      message: `缺少参数: ${checks}`
    })
  }
  const { nickname,  mobile, id } = req.body
  let user_pic
  const GetUserPic = await QueryDb(`select user_pic from admin where id = ${id}`)
  user_pic = GetUserPic[0].user_pic
  if(req.files){
    const imgName = await savePhotoFile(req.files.file)
    user_pic =  imgName
  }


  const regex = /^[1-9]\d{10}$/
  if (!regex.test(mobile)) return res.cc('手机号格式不正确')

  try {
    await mysql2.writer(`UPDATE admin SET nickname = ?, user_pic = ?, mobile = ? WHERE id = ?`, [nickname, user_pic, mobile, Number(id)])
    return res.send({
      status: 1,
      message: '更新成功'
    })
  } catch (error) {
    logger.error(error)
    return res.cc(error)
  }
}
exports.enableAdmin = async (req,res) =>{
  const { id } = req.body
  if(!id){
    return res.send({
      status: 0,
      message: `缺少参数`
    })
  }
  if(id == 1){
    return res.send({
      status: 0,
      message: `该账号是最高权限，不能被禁用`
    })
  }
  const adminInfo = await QueryDb(`select is_able from admin where id = ${id}`)
  let NewStatus = adminInfo[0].is_able == 1 ? 0 : 1
  const upAdminInfo = await QueryDb(`UPDATE admin SET is_able = ${NewStatus} where id = ${id}`)
  return res.send({
    status: 1,
    message: `操作成功`,
    data:{
      is_able:NewStatus
    }
  })
}
exports.deleteRolePermissions = async(req,res) =>{
  if(req.user.id != 1){
    return res.send({
      status:0,
      message:'你不是最高权限者'
    })
  }
  if(!req.body.id){
    return res.send({
      status:0,
      message:"缺少参数"
    })
  }
  try {
    const deleteRolePermissionsRes = await QueryDb(`delete from roles where id = '${req.body.id}'`)
    res.send({
      status:1,
      message:'删除成功'
    })
  } catch (error) {
    logger.error(error.message)
    res.send({
      status:0,
      message:'删除失败,其它业务正在使用该角色'
    })
  }
  

}
